import Taro from "@tarojs/taro";
import { loginByWechat, updateToken } from "./login";
import apiUrl from "./urls";
import { post } from "./request/request";
import { bindStaffRelationship } from "./staffRelationship";
import { getStoreData, handleStore } from "./init";
import { getAuthorizeStatus } from "../service/data";
import { AUTHORIZEPHONESTATUS, MOBILE } from "../constants/userInfo";

const authorizePhoneStatus = {
  authorizeStatus: 0, // 授权状态 0:未授权 1:已授权
  switchStatus: 0, // 小程序手机号授权开关状态标识 0:授权关 1授权开 仅IM使用
  mobile: null, // 授权的手机号
};

function getPhoneNumber(options, bindStaff = true) {
  return new Promise((resolve, reject) => {
    loginByWechat()
      .then((code) => {
        const c = getStoreData('card');
        const u = getStoreData('userInfo');
        post(
          apiUrl.authPhoneUrl,
          {
            code,
            ...options,
            cardId: c.__cardId,
          },
          {
            silentFail: false,
            showLoading: true,
          }
        )
          .then((res) => {
            console.log("授权手机号res===》", res);
            const { mobile, userId } = res;
            authorizePhoneStatus.authorizeStatus = 1;
            authorizePhoneStatus.mobile = mobile;
            handleStore(AUTHORIZEPHONESTATUS,authorizePhoneStatus)
            handleStore(MOBILE,mobile)
            Taro.setStorageSync("v2_mobile", mobile);
            // 授权后进行绑定员工关系,只有是政府人员才会绑定
            if (u.userInfo.gov) {
              bindStaffRelationship(mobile)
                .then((r) => {
                  console.log("授权手机号绑定成功", r);
                })
                .catch((r) => {
                  console.log("授权手机号绑定错误", r.data.msg);
                  // reject(res.data.msg)
                });
            }
            // 如果返回来的userId 和之前的不一样，需要刷新token。因为政府授权手机号的时候如果是政府人员的话token 会变
            if (userId !== u.userInfo.userId) {
              updateToken("1").then(); // 手机号刷新token的时候需要传 authorizePhone = 1 来刷新
              bindStaffRelationship(mobile)
                .then((r) => {
                  console.log("授权手机号绑定成功", r);
                })
                .catch((r) => {
                  console.log("授权手机号绑定错误", r.data.msg);
                  // reject(res.data.msg)
                });
            } else {
              updateToken().then();
            }
            resolve(mobile);
          })
          .catch((error) => reject(error));
      })
      .catch((error) => reject(error));
  });
}

function getAuthorizePhone() {
  return new Promise((resolve, reject) => {
    const m = Taro.getStorageSync("v2_mobile");
    if (m) {
      authorizePhoneStatus.authorizeStatus = 1;
      authorizePhoneStatus.mobile = m;
    }
    if (authorizePhoneStatus.authorizeStatus === 1) {
      resolve({ ...authorizePhoneStatus });
      return;
    }

    getAuthorizeStatus().then(
      (res) => {
        const { authorizeStatus, switchStatus, mobile } = res;
        Object.assign(authorizePhoneStatus, {
          authorizeStatus,
          switchStatus,
          mobile,
        });
        resolve({ authorizeStatus, switchStatus, mobile });
      },
      (error) => reject(error)
    );
  });
}

export { getAuthorizePhone, getPhoneNumber };
